from flask import session, render_template, request, redirect
from app.models.UserModel import UserModel
from functools import wraps


class UserAuth:

    @staticmethod
    def __getUserInfo() -> any:
        result = session.get('userinfo', False)
        return result

    @staticmethod
    def isLogin():
        '''
        是否已登录
        :return:
        '''
        UserInfo = UserAuth.__getUserInfo()
        if UserInfo == False or UserInfo == {}:
            return False
        else:
            return UserInfo

    @staticmethod
    def isAdmin():
        '''
        是否为管理员
        :return:
        '''
        UserInfo = UserAuth.__getUserInfo()
        if UserInfo == False or UserInfo == {}:
            return False
        elif UserInfo.get('isadmin') == 1:
            return True
        else:
            return False

    @staticmethod
    def isLogin_dec(func):
        '''
        函数装饰器，用于验证用户登录状态
        :param func:
        :return:
        '''

        @wraps(func)
        def check_login(*args, **kwargs):
            cls = func(*args, **kwargs)
            UserInfo = UserAuth.__getUserInfo()
            if UserInfo == False or UserInfo == {}:
                return render_template('error.html', message='请登录后再执行操作！', url='/home')
            else:
                return cls

        return check_login
